package org.mineground.commands.player;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.mineground.Main;
import org.mineground.handlers.NameBanHandler;
import org.mineground.player.MinegroundPlayer;
import org.mineground.player.PasswordHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @name Login.java
 * @author Daniel Koenen (2012)
 * 
 */
public class Login implements CommandExecutor {
    private static final Logger ExceptionLogger = LoggerFactory.getLogger(Login.class);
    
    public void triggerCommandExecution(Player player, String command, String[] arguments) {
        onCommand(player, null, command, arguments);
    }
    
    @Override
    public boolean onCommand(CommandSender cs, Command cmnd, String string, String[] arguments) {
        Player player = (Player) cs;

        if (arguments.length < 1) {
            player.sendMessage(ChatColor.RED + "* Usage: '/login <password>'");
            return true;
        }

        try {
            if (!Main.getInstance().containsPlayer(player)) {
                player.sendMessage(ChatColor.RED + "* Error: You are not registered, please do so now at www.mineground.com/register!");
                return true;
            }
            
            MinegroundPlayer playerInstance = Main.getInstance().getPlayer(player);
            
            if (playerInstance.isLoggedIn()) {
                player.sendMessage(ChatColor.RED + "* Error: You are already logged in.");
                return true;
            }

            PreparedStatement queryStatement = Main.getInstance().getDatabaseHandler().getConnection().prepareStatement("SELECT p.salt, s.password FROM lvm_players p LEFT JOIN lvm_player_settings s ON s.player_id = p.player_id WHERE s.player_id = ?");
            queryStatement.setInt(1, playerInstance.getProfileId());
            queryStatement.execute();

            ResultSet queryResult = queryStatement.getResultSet();
            
            if (!queryResult.next()) {
                return true;
            }

            String passwordSalt = queryResult.getString(1);
            String savedPassword = queryResult.getString(2);
            String playerPassword = PasswordHandler.getPasswordHash(arguments[0], passwordSalt);

            queryStatement.close();

            if (!savedPassword.equals(playerPassword)) {
                player.sendMessage(ChatColor.RED + "* Error: Invalid password.");

                playerInstance.addInvalidLoginAttempt();

                short loginAttempts = playerInstance.getInvalidLoginAttempts();
                player.sendMessage(ChatColor.RED + "Attempt " + playerInstance.getInvalidLoginAttempts() + " of 3.");

                if (loginAttempts == 3) {
                    NameBanHandler.kickPlayer(player.getName(), "Server", "Invalid log in attempt.");
                }

                return true;
            }

            playerInstance.logIn();
            player.sendMessage(ChatColor.DARK_GREEN + "You have been logged in successfuly, have fun!");
        } 
        
        catch (Exception exception) {
            ExceptionLogger.error("Exception caught", exception);
            player.sendMessage(ChatColor.RED + "* Error: An unknown error occured when trying to log in, please contact an administrator.");
        }

        return true;
    }
}
